package com.bootcamp.s3_1013.database._1018_transaction;

import com.bootcamp.s3_1013.database.utils.JDBCUtils;

import java.sql.*;

/**
 * @program: myClassCode
 * @description: use prepareStatement to avoid security issue
 * @author: Keyu Li
 * @create: 2021-10-18 10:54
 **/

public class Demo2_prepareStatement {
    public static void main(String[] args) {
        //get connection
        Connection connection = JDBCUtils.getConnection();
        //query whether exist
        String ename="tom' or 1 and ename='";
        String job="clerk";
        // use statement to login
        String success1 = loginByStatement(connection,ename,job)?"success!":"fail!";
        // use preparedStatement to login
        String success2 = loginByPreparedStatement(connection, ename, job) ? "success!" : "fail!";
        System.out.println("statement:\t\t\t" + success1+"\npreparedStatement:\t"+success2);
    }

    public static boolean loginByStatement(Connection c,String ename,String job){
        try {
            Statement statement = c.createStatement();
            String sql="select * from emp where ename='"+ename+"' and job='"+job+"'";
            ResultSet resultSet = statement.executeQuery(sql);
            if (resultSet.next()) return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
        return false;
    }

    public static boolean loginByPreparedStatement(Connection c,String ename,String job){
        try {
            PreparedStatement preparedStatement = c.prepareStatement("select * from emp where ename=? and job=?");
            preparedStatement.setString(1,ename);
            preparedStatement.setString(2,job);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
        return false;
    }
}
